<?php
namespace app\admin\logic;

use app\common\logic\Base;
use think\Db;
use think\facade\App;

class Order extends Base {

    /**
     * @desc 订单列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsOrder($params) {
        $where = [];
        if($params['orderNo']) {
            $where[] = ['go_order_no', '=', $params['orderNo']];
        }
        
        if($params['goodsName']) {
            $where[] = ['go_goods_name', 'like', '%' .$params['goodsName']. '%'];
        }
        
        if($params['userName']) {
            $userId = App::model('User')
                ->where('user_phone', 'like', '%'.$params['userName'].'%')
                ->whereOr('user_email', 'like', '%'.$params['userName'].'%')
                ->value('user_id');
            if($userId) {
                $where[] = ['go_user_id', '=', $userId];
            }
        }
        
        $list = App::model('GoodsOrder')
            ->where($where)
            ->order('go_order_id', 'desc')
            ->paginate($params['pageSize']);
    
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'go');
    
            $userIds = array_unique(array_column($list, 'userId'));
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
            foreach ($list as $k => $v) {
                $list[$k]['userName'] = $userInfo[$v['userId']]['user_phone'] ?: $userInfo[$v['userId']]['user_email'];
            }
        }

        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    /**
     * @desc 订单列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rechargeOrder($params) {
        $where = [];
        if($params['orderNo']) {
            $where[] = ['ro_order_no', '=', $params['orderNo']];
        }
    
        if($params['accountName']) {
            $where[] = ['ro_account_name', 'like', '%' .$params['accountName']. '%'];
        }
        
        if($params['userName']) {
            $userId = App::model('User')
                ->where('user_phone', 'like', '%'.$params['userName'].'%')
                ->whereOr('user_email', 'like', '%'.$params['userName'].'%')
                ->value('user_id');
            if($userId) {
                $where[] = ['ro_user_id', '=', $userId];
            }
        }
        
        $list = App::model('RechargeOrder')
            ->where($where)
            ->order('ro_recharge_id', 'desc')
            ->paginate($params['pageSize']);
    
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'ro');
    
            $userIds = array_unique(array_column($list, 'userId'));
            $memberIds = array_unique(array_column($list, 'memberId'));
            $userInfo = App::model('User')
                ->where('user_id', 'in', $userIds)
                ->column('user_phone,user_email', 'user_id');
    
            $memberInfo = App::model('AuthMember')
                ->where('am_member_id', 'in', $memberIds)
                ->column('am_username', 'am_member_id');
            
            foreach ($list as $k => $v) {
                $list[$k]['userName'] = $userInfo[$v['userId']]['user_phone'] ?: $userInfo[$v['userId']]['user_email'];
                $list[$k]['memberName'] = $memberInfo[$v['memberId']];
            }
        }
        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
    
    /**
     * @desc 锁定订单
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function locking($params, $memberInfo) {
        $rechargeInfo = App::model('RechargeOrder')
            ->where('ro_recharge_id', '=', $params['id'])
            ->find();
    
        //判断订单信息是否存在
        if(!$rechargeInfo) {
            $this->errorCode = EC_HOME_RECHARGE_ORDER_NOT_EXIST;
            return false;
        }
        
        //判断是否非法操作
        if($rechargeInfo['ro_status'] !== RECHARGE_ORDER_STATUS_DEFAULT) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        $rechargeOrder = App::model('RechargeOrder')
            ->where('ro_recharge_id', '=', $params['id'])
            ->update([
                'ro_member_id'     => $memberInfo['memberId'],
                'ro_status'        => RECHARGE_ORDER_STATUS_LOCKING,
                'ro_locking_time'  => date('Y-m-d H:i:s'),
                'ro_modify_time'   => date('Y-m-d H:i:s')
            ]);
    
        if($rechargeOrder === false) {
            //添加行为日志
            App::model('common/BehaviorLog')->addLog([
                'controller' => 'Order',
                'action'     => 'locking',
                'message'    => '锁定充值订单ID:'.$params['id'],
                'username'   => $memberInfo['username'],
                'memberId'   => $memberInfo['memberId'],
            ]);
            
            Db::commit();
            return true;
        }
        return true;
    }
    
    /**
     * @desc 订单，确认
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function confirm($params, $memberInfo) {
        $rechargeInfo = App::model('RechargeOrder')
                    ->where('ro_recharge_id', '=', $params['id'])
                    ->find();
        
        //判断订单是否存在
        if(!$rechargeInfo) {
            $this->errorCode = EC_AD_RECHARGE_ORDER_NOT_EXIST;
            return false;
        }
    
        //如果订单不是锁定状态就不能进行任何操作
        if($rechargeInfo['ro_status'] != RECHARGE_ORDER_STATUS_LOCKING) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        //判断该订单操作人是否匹配
        if($memberInfo['memberId'] != $rechargeInfo['ro_member_id']) {
            $this->errorCode = EC_AD_RECHARGE_ORDER_ALREADY_LOCKING;
            return false;
        }
        
        $goodsOrderInfo = App::model('GoodsOrder')
                    ->where('go_order_id', '=', $rechargeInfo['ro_goods_order_id'])
                    ->find();
        
        //判断商品信息是否存在
        if(!$goodsOrderInfo) {
            $this->errorCode = EC_HOME_GOODS_ORDER_NOT_EXIST;
            return false;
        }
        
        Db::startTrans();
        //生成充值订单
        $rechargeOrder = App::model('RechargeOrder')
                    ->where('ro_recharge_id', '=', $params['id'])
                    ->update([
                        'ro_status'        => RECHARGE_ORDER_STATUS_SUCCESS,
                        'ro_recharge_time' => date('Y-m-d H:i:s'),
                        'ro_confirm_time'  => date('Y-m-d H:i:s'),
                        'ro_modify_time'   => date('Y-m-d H:i:s')
                    ]);
        
        //生成商品订单
        $goodsOrder = App::model('GoodsOrder')
                    ->where('go_order_id', '=', $rechargeInfo['ro_goods_order_id'])
                    ->update([
                        'go_pay_time'     => date('Y-m-d H:i:s'),
                        'go_modify_time'  => date('Y-m-d H:i:s'),
                        'go_pay_status'   => GOODS_ORDER_PAY_STATUS_SUCCESS
                    ]);
        
        //查询用户当前推荐人，如果有推荐人就进行分润
        $userInfo = App::model('User')
            ->where('user_id', '=', $rechargeInfo['ro_user_id'])
            ->find();
        if($userInfo['user_pid'] > 0) {
            $commission = App::model('UserIncome')->calcCommission($goodsOrderInfo['go_buy_count']);
            //生成佣金记录
            App::model('UserIncome')->insert([
                'ui_owner_id'      => $userInfo['user_pid'],
                'ui_order_user_id' => $goodsOrderInfo['go_user_id'],
                'ui_order_id'      => $goodsOrderInfo['go_order_id'],
                'ui_buy_count'     => $goodsOrderInfo['go_buy_count'],
                'ui_name'          => '推广佣金',
                'ui_amount'        => $commission,
                'ui_create_time'   => date('Y-m-d H:i:s'),
            ]);
            
            //生成金流记录
            App::model('UserWallet')->incBalance($userInfo['user_pid'], $commission, 'hs_goods_order:'.$rechargeInfo['ro_recharge_no'], '佣金结算');
        }
        
        //添加设备数
        $device = App::model('User')
            ->where('user_id', '=', $rechargeInfo['ro_user_id'])
            ->setInc('user_device_num', $goodsOrderInfo['go_buy_count']);
        
        if($rechargeOrder && $goodsOrder && $device) {
            //添加行为日志
            App::model('common/BehaviorLog')->addLog([
                'controller' => 'Order',
                'action'     => 'confirm',
                'message'    => '确认充值订单ID:'.$params['id'],
                'username'   => $memberInfo['username'],
                'memberId'   => $memberInfo['memberId'],
            ]);
            
            Db::commit();
            return true;
        }else{
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    }
    
    /**
     * @desc 订单，确认
     * @param array $params
     * @param array $memberInfo
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refuse($params, $memberInfo) {
        $rechargeInfo = App::model('RechargeOrder')
            ->where('ro_recharge_id', '=', $params['id'])
            ->find();
        
        if(!$rechargeInfo) {
            $this->errorCode = EC_AD_RECHARGE_ORDER_NOT_EXIST;
            return false;
        }
    
        //如果订单不是锁定状态就不能进行任何操作
        if($rechargeInfo['ro_status'] != RECHARGE_ORDER_STATUS_LOCKING) {
            $this->errorCode = EC_ILLEGAL_OPERATION;
            return false;
        }
        
        //判断该订单操作人是否匹配
        if($memberInfo['memberId'] != $rechargeInfo['ro_member_id']) {
            $this->errorCode = EC_AD_RECHARGE_ORDER_ALREADY_LOCKING;
            return false;
        }
        
        Db::startTrans();
        $rechargeOrder = App::model('RechargeOrder')
            ->where('ro_recharge_id', '=', $params['id'])
            ->update([
                'ro_status'        => RECHARGE_ORDER_STATUS_FAIL,
                'ro_recharge_time' => date('Y-m-d H:i:s'),
                'ro_confirm_time'  => date('Y-m-d H:i:s')
            ]);
        
        $goodsOrder = App::model('GoodsOrder')
            ->where('go_order_id', '=', $rechargeInfo['ro_goods_order_id'])
            ->update([
                'go_pay_time'     => date('Y-m-d H:i:s'),
                'go_pay_type'     => GOODS_ORDER_PAY_TYPE_BANK_TRANSFER,
                'go_pay_status'   => GOODS_ORDER_PAY_STATUS_FAIL
            ]);
        
        if($rechargeOrder && $goodsOrder) {
            //添加行为日志
            App::model('common/BehaviorLog')->addLog([
                'controller' => 'Order',
                'action'     => 'refuse',
                'message'    => '拒绝充值订单ID:'.$params['id'],
                'username'   => $memberInfo['username'],
                'memberId'   => $memberInfo['memberId'],
            ]);
            
            Db::commit();
            return true;
        }else{
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    }
}